package me.firstapp.api.base;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.utils.StrUtils;

@Service
public class BaseApi {

	/**
	 * 输出字符串
	 * 
	 * @param response
	 * @param msg
	 */
	protected void renderText(HttpServletResponse response, String msg) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 输出json
	 * 
	 * @param response
	 * @param obj
	 */
	protected void renderJson(HttpServletResponse response, Object obj) {
		this.renderText(response, JSONObject.toJSONString(obj));
	}

	/**
	 * 校验验证码
	 * 
	 * @param stringRedisTemplate
	 * @param code
	 * @param email
	 */
	protected void verifyCode(StringRedisTemplate stringRedisTemplate, String code, String email) {
		if (StrUtils.isNULL(code)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "验证码");
		}
		String _code = stringRedisTemplate.opsForValue().get(email);
		if (StrUtils.isNULL(_code) || !_code.equals(code)) {
			throw new ServiceException(StatusHouse.VERIFY_CODE_WRONG);
		}
	}
}
